package com.example.demo.zookeeper.mytest.lock;

import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * @author liweizhi
 * @date 2020/6/24
 */
public class TestLock {
    private ZooKeeper zk;

    @Before
    public void connect() {
        zk = ZkLockUtil.newZookeeper();
    }

    @After
    public void close() {
        try {
            zk.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testLock() {

        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                String name = Thread.currentThread().getName();
                LockWatcherCallback lockWatcherCallback = new LockWatcherCallback();
                lockWatcherCallback.setThreadName(name);
                lockWatcherCallback.setZooKeeper(zk);
                lockWatcherCallback.lock();
                System.out.println(name + " working start ");
                /*try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/
                System.out.println(name + " working end ");
                lockWatcherCallback.unLock();
            }).start();
        }
//        zk.create(ZkLockUtil.theLockPath, )
        try {
            TimeUnit.DAYS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
